import axios, { type AxiosError, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import type { ApiResponse } from './index';

const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000,
});

http.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('tcm-ai-token');
    if (token && config.headers) {
      config.headers.Authorization = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => Promise.reject(error),
);

http.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const res = response.data;
    if (typeof res?.code === 'number' && res.code !== 0) {
      if (res.code === 401) {
        localStorage.removeItem('tcm-ai-token');
        ElMessage.error(res.message || '登录状态已过期');
        window.location.href = '/login';
        return Promise.reject(res);
      }
      if (res.message) {
        ElMessage.error(res.message);
      } else {
        ElMessage.error('请求失败，请稍后重试');
      }
      return Promise.reject(res);
    }
    return res;
  },
  (error: AxiosError<ApiResponse>) => {
    const status = error.response?.status;
    const message = error.response?.data?.message || error.message || '请求失败';
    if (status === 401) {
      localStorage.removeItem('tcm-ai-token');
      ElMessage.error('登录状态已过期，请重新登录');
      window.location.href = '/login';
    } else {
      if (status === 413) {
        ElMessage.error('上传文件过大，请压缩后重试');
      } else if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查网络后重试');
      } else if (!error.response) {
        ElMessage.error('网络异常，请检查连接');
      } else {
        ElMessage.error(message);
      }
    }
    return Promise.reject(error);
  },
);

export default http;

